import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

/**
 * 修稿默认push 方法, 防止重复跳转
 **/
const orginal = VueRouter.prototype.push;

VueRouter.prototype.push = function push(localtion) {
  return orginal.call(this, localtion).catch(err => err);
};

// 安装插件
Vue.use(VueRouter);

const User = () => import(/* webpackChunkName: "user" */ '../views/User.vue');

// 配置映射关系
const routes = [
  {
    // 缺省值重定向
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    meta: {
      title: '首页'
    },
    component: Home,
    children: [
      {
        path: 'news',
        name: 'News',
        component: () => import(/* webpackChunkName: "news" */ '../views/home/News')
      },
      {
        path: 'message',
        name: 'Message',
        component: () => import(/* webpackChunkName: "message" */ '../views/home/Message')
      }
    ]
  },
  {
    path: '/about',
    name: 'About',
    meta: {
      title: '关于'
    },
    // 路由守卫
    beforeEnter: (to, from, next) => {
      next();
    },
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/user/:id',
    name: 'User',
    meta: {
      title: '用户'
    },
    component: User
  },
  {
    path: '/user',
    name: 'User',
    component: User
  }
];

// 创建路由对象
const router = new VueRouter({
  routes,
  mode: "history", // 切换为history模式, 默认是hash模式
  linkActiveClass: "active" // router-link 激活状态的 class 名称
});

/**
 * 从from路由跳转到to路由
 * 全局导航守卫(前置钩子)
 */
router.beforeEach((to, from, next) => {
  // to.meta 修复了, 可以获取到定义的 meta, 而不需要用 to.matched 里面获取
  document.title = to.meta ? to.meta.title || to.name : to.name;
  // 必须调用 next(), 不然会丢失默认操作
  next();
});

/**
 * 全局后置钩子(跳转之后调用)
 */
router.afterEach((to, from) => {
  // document.writeln("<p>后置钩子回调</p>");
});

// 导出路由对象
export default router
